#include "mainwindow.h"
#include "ui_mainwindow.h"

static bool firstStart=true;

MainWindow::MainWindow(QString _roomNo,QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    myRoom(_roomNo),
    mySocket(new QTcpSocket(nullptr)),
    dataSize(0),
    t_wind(1),
    t_temperature(25),
    timer(new QTimer(this)),
    hostAddress(QString("192.168.220.129")),
    portToConnect(8080)
{
    ui->setupUi(this);
    ui->label_14->setText(QString().setNum(ui->dial->value()));
    in.setDevice(mySocket);
    in.setVersion(QDataStream::Qt_5_0);

    connect(this->ui->comboBox,static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),this,&MainWindow::setTWind);
    connect(this->ui->dial,&QDial::valueChanged,this,&MainWindow::setTTemperature);
    connect(this->ui->pushButton,&QPushButton::clicked,this,&MainWindow::launch);
}

MainWindow::~MainWindow()
{
    delete ui;
    delete mySocket;
    delete timer;
}

void MainWindow::connectToHost()
{
    mySocket->connectToHost(hostAddress, portToConnect);
    bool isConnected = mySocket->waitForConnected();
    if (!isConnected) {
        QMessageBox::critical(this, "Error", "Can NOT connect to server. Please try again later.");
        exit(1);
    }
}

void MainWindow::sendBlock(QByteArray *p_block)
{
    this->mySocket->write(*p_block);
    delete p_block;
    p_block = nullptr;
}

void MainWindow::response()
{
    while (mySocket->bytesAvailable() > 0) {
        /*if (dataSize == 0)
        {
            if (mySocket->bytesAvailable() < sizeof(quint32)) {
                return;
            }
            in >> dataSize;
            dataSize=qToLittleEndian(dataSize);
        }
        if(mySocket->bytesAvailable()<dataSize){
            break;
        }
        else{*/
            QJsonValue value;
            QJsonObject obj;
            QByteArray a;
            a=mySocket->read(1024);
            qDebug()<<"recv data "<<a.data();
            QJsonParseError json_error;
            QJsonDocument text = QJsonDocument::fromJson(a, &json_error);
            if(json_error.error == QJsonParseError::NoError){
                if(text.isObject()){
                    obj=text.object();
                    value=obj.take("switch");
                    bool isOpen=(value.toInt()==1)?true:false;
                    value=obj.take("temperature");
                    double temperature=value.toDouble();
                    value=obj.take("wind");
                    int wind=value.toInt();
                    value=obj.take("cost");
                    double cost=value.toDouble();
                    value=obj.take("isServed");
                    bool isServed=((wind==0||wind==-1)?false:true);
                    emit finishParse(isOpen,temperature,wind,cost,isServed);
                }
            }
            dataSize=0;

    }
}

void MainWindow::showStatus()
{
    this->ui->label_3->clear();
    this->ui->label_4->clear();
    this->ui->label_7->clear();
    this->ui->label_9->clear();
    this->ui->label_3->setText(this->myRoom.getIsOpen()?QString("Yes"):QString("false"));
    if(this->myRoom.getIsOpen()){
        this->ui->label_4->setText(this->myRoom.getIsServed()?QString("Yes"):QString("No"));
    }
    this->ui->label_9->setText(QString().setNum(this->myRoom.getCost()));
    this->ui->label_7->setText(QString().setNum(this->myRoom.getTemperature()));
}

void MainWindow::setTWind(int idx)
{
    this->t_wind=this->ui->comboBox->currentText().toInt();
    qDebug()<<"wind "<<this->t_wind;
}

void MainWindow::setTTemperature()
{
    this->t_temperature=this->ui->dial->value();
    this->ui->label_14->setText(QString().setNum(this->t_temperature));
}

void MainWindow::setData()
{
    this->myRoom.setSTemperature(this->t_temperature);
    this->myRoom.setSWind(this->t_wind);
    this->myRoom.encapsulateRequest();
}

void MainWindow::launch()
{
    if(firstStart==true){
        this->connectToHost();
        connect(&myRoom,&room::finishEncapsulation,this,&MainWindow::sendBlock);
        connect(this->mySocket,&QTcpSocket::readyRead,this,&MainWindow::response);
        connect(this,&MainWindow::finishParse,&myRoom,&room::setValue);
        connect(timer,&QTimer::timeout,&myRoom,&room::encapsulateNotification);
        connect(timer,&QTimer::timeout,this,&MainWindow::showStatus);
        connect(this->ui->pushButton_2,&QPushButton::clicked,this,&MainWindow::setData);
        timer->start(1000);
        firstStart=false;
    }
    if(this->myRoom.getIsOpen()){
        this->myRoom.setIsOpen(false);
        this->myRoom.encapsulateRequest();
    }
    else if(!(this->myRoom.getIsOpen())){
        this->myRoom.setIsOpen(true);
        this->myRoom.encapsulateRequest();
    }
}
